// http.js uni.request 二次封装

import config from './config.js'
// import message from './message.js'

// URL 校验和处理函数
function processUrl(url) {
    const urlReg = /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/
    if (urlReg.test(url)) {
        return url
    }
    // 如果不是完整的 URL，则添加 baseUrl
    const baseUrl = config.PARAM.BASE_URL
    return `${baseUrl}${url}`
}

const http = (options = {}) => {
    const { 
        url, 
        method = 'GET', 
        data,
        contentType = 'application/x-www-form-urlencoded'
    } = options
    
    return new Promise((resolve, reject) => {
        // 获取 token
        const token = uni.getStorageSync('token')
        const header = {
            'Content-Type': contentType,
            ...(token ? { 'Authorization': `Bearer ${token}` } : {})
        }
        
        uni.request({
            url: processUrl(url),
            method: method.toUpperCase(),
            data: data,
            header: header,
            success: (res) => {
                // 处理响应
                if (res.statusCode === 401) {
                    // token 失效，清除token并跳转到登录页
                    uni.removeStorageSync('token')
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    reject(new Error('未授权，请重新登录'))
                    return
                }
                
                console.log(`request:${method}请求成功`, { url, response: res.data })
                resolve(res.data)
            },
            fail: (err) => {
                console.error('请求失败')
                console.error(`request:${method}请求失败`, { url, error: err })
                reject(err)
            }
        })
    })
}

export default http

